<?php

/**
 * door actions.
 *
 * @package    glcci
 * @subpackage door
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class doorActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
  	$this->setLayout('loginLayout');
  	if($request->isMethod('POST')) {
  		$sess = $this->getUser();
  		$dao = new DAO();
  		$pw = md5($dao->getEscapedSQLString(trim($request->getPostParameter('password'))));
  		$email = $dao->getEscapedSQLString(trim(strtolower($request->getPostParameter('email'))));
  		$dao->query("SELECT * FROM user WHERE email='{$email}' AND password='{$pw}'");
  		if($dao->queryOK()) {
  			$user = $dao->next();
  			$dao->query("SELECT last_login_ts FROM user WHERE email='{$user['email']}'");
  			// I know that there is a record in the DB with this email, so no need to check
  			$ts_row = $dao->next();
  			$last_login = is_null($ts_row['last_login_ts']) ? 'N/A' : date('M jS Y @ g:i:s T', $ts_row['last_login_ts']);
  			$dao->query("UPDATE user SET last_login_ts=UNIX_TIMESTAMP() WHERE email='{$user['email']}'");
  			$sess->setAttribute('user_role', $user['role']);
  			$sess->setAttribute('user_name', "{$user['first_name']} {$user['last_name']}");
  			$sess->setAttribute('user_email', $user['email']);
  			$sess->setAttribute('user_ll', $last_login);
  			$sess->setAuthenticated(true);
  			$sess->addCredential($user['role']);
  		} else {
  			$sess->getAttributeHolder()->clear();
  			$sess->setAuthenticated(false);
  			$sess->setFlash('login_error', 'Invalid email and/or password!');
  		}
  		$this->redirect($this->getContext()->getRouting()->getCurrentInternalUri(true));
  	} else return sfView::SUCCESS;
  }
  
  
  public function executeLogout(sfWebRequest $request) {
  	$sess = $this->getUser();
  	$sess->setAuthenticated(false);
  	$sess->getAttributeHolder()->clear();
  	$sess->setFlash('login_error', 'Goodbye.');
  	$this->redirect('@home'); // once appropriate switch to @control
  	return sfView::SUCCESS;
  }
  
  public function executeNotFound(sfWebRequest $request) {
  	return sfView::SUCCESS;
  }
  
  
}
